<?php


namespace app\admin\controller;


use app\admin\library\Auth;
use app\admin\model\AdminLog;
use app\BaseController;
use app\service\AuthService;
use thans\jwt\facade\JWTAuth;
use think\addons\Service;
use think\Cache;
use think\facade\Config;
use think\facade\Event;
use think\facade\Session;
use think\facade\View;
use think\Request;
use think\route\dispatch\Controller;
use think\Validate;
use Zewail\Api\Facades\JWT;

class Login
{
    public function index(Request $request)
    {
        $is_mobile = wp_is_mobile();
        if ($is_mobile == true){
            $verify_type = 1;
        }else{
            $verify_type = Config::get('app.verify_type');
        }
        $url = $request->get('url', '/admin/index/index');
        if ($request->isAjax()){
            $username = $request->param('username');
            $password = $request->param('password');
            $keeplogin = $request->param('keeplogin');
            $token = $request->param('__token__');
            $rule = [
                'username'  => 'require|length:3,30',
                'password'  => 'require|length:3,30',
                '__token__' => 'require|token',
            ];
            $data = [
                'username'  => $username,
                'password'  => $password,
                '__token__' => $token,
            ];
            $validate = new Validate($rule, [], ['username' => ('Username'), 'password' => ('Password'), 'captcha' => ('Captcha')]);
            $result = $validate->check($data);
            if (!$result) {
                $this->error($validate->getError(), $url, ['token' => $request->buildToken()]);
            }
//            AdminLog::setTitle(__('Login'));
            // 用户信息验证
            try {
                if ($verify_type == 1) {
                    $code = $request->param("vercode");
                    if (!captcha_check($code)) {
                        return json(['code' => -4, 'url' => '', 'msg' => '验证码错误']);
                    }
                }
                $result = Auth::instance()->login($username, $password, $keeplogin ? 86400 : 30);
                if ($result == true) {
                    return json(['code' => 1, 'url' => '/admin/index/index', 'msg' => '登录成功！']);
                } else {
                    return json(['code' => -1, 'url' => '', 'msg' => '登录失败！']);
                }
            } catch (\Exception $e) {
                return json(['code' => $e->getCode(), 'url' => '', 'msg' => $e->getMessage()]);
            }
        }

        // 根据客户端的cookie,判断是否可以自动登录
        if (Auth::instance()->autologin()) {
            return redirect('/admin/index/index');
        }
        $background = Config::get('app.login_background');
        $background = stripos($background, 'http') === 0 ? $background : config('site.cdnurl') . $background;
        View::assign('background', $background);
        View::assign('verify_type', $verify_type);
        return View::fetch();
    }


    /**
     * @param Request $request
     * @return \think\response\Json
     * 登录验证
     */
    public function doLogin(Request $request)
    {
        $url = $request->get('url', 'index/index');

        if ($request->isAjax()){
            $this->auth = Auth::instance();
            $verify_type = Config::get('app.verify_type');
            $username = $request->param('username');
            $password = $request->param('password');
            $remember = $request->param('remember');
            $token = $request->param('__token__');
            if (isset($remember)) {
                $keeplogin = 1;
            } else {
                $keeplogin = null;
            }
            $rule = [
                'username'  => 'require|length:3,30',
                'password'  => 'require|length:3,30',
                '__token__' => 'require|token',
            ];
            $data = [
                'username'  => $username,
                'password'  => $password,
                '__token__' => $token,
            ];
            $validate = new Validate($rule, [], ['username' => ('Username'), 'password' => ('Password'), 'captcha' => ('Captcha')]);
            $result = $validate->check($data);
            if (!$result) {
                $this->error($validate->getError(), $url, ['token' => $this->request->token()]);
            }
            AdminLog::setTitle(__('Login'));
            // 用户信息验证
            try {
                if ($verify_type == 1) {
                    $code = $request->param("vercode");
                    if (!captcha_check($code)) {
                        return json(['code' => -4, 'url' => '', 'msg' => '验证码错误']);
                    }
                }
                $result = $this->auth->login($username, $password, $keeplogin ? 86400 : 30);
                if ($result == true) {

                    return json(['code' => 1, 'url' => '/admin/index/index', 'msg' => '登录成功！']);
                } else {
                    return json(['code' => -1, 'url' => '', 'msg' => '登录失败！']);
                }
            } catch (\Exception $e) {
                return json(['code' => $e->getCode(), 'url' => '', 'msg' => $e->getMessage()]);
            }
        }
    }

    /**
     * 注销登录 使用ajax 存在BUG  要使用中间件
     */
    public function logout()
    {
        $this->auth = Auth::instance();
        $this->auth->logout();
        return json(['code' => 1, 'url' => '/admin/login/index', 'msg' => '退出成功！']);
    }

    /**
     * 清空系统缓存
     */
    public function wipecache()
    {
        rmdirs(runtime_path(), false);
        \think\facade\Cache::clear();
        return json(['code' => 200, 'url' => '', 'msg' => '清除成功！']);
    }

}